from logicaltool.BaseTools.file_tools import FileTools
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
config_file = BaseDir.get_new_path(curPath, "db.ini")
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "jstorbook", "download", "cover")

"""
将上一步生成的文件放入hadoop中解析 cover以base64编码，这一步将编码装换成图片
"""


class FileToolsDB3(FileTools):
    def __init__(self):
        super(FileToolsDB3, self).__init__()

    def create_temp_tab(self):
        sql = "DROP TABLE IF EXISTS `temp1`"
        self.sqlite3utiles.ExeSqlliteSql(sql)
        sql = "CREATE TABLE `temp1` (`rawid` TEXT,`cover` TEXT)"
        self.sqlite3utiles.ExeSqlliteSql(sql)

    def deal_sqlite3_select(self, rows):
        listsql = []
        for rawid, cover in rows:
            filePath = BaseDir.get_new_path(sPath, rawid + ".jpg")
            fileDir = filePath.split("/")[0]
            if not BaseDir.is_dir_exists(fileDir):
                BaseDir.create_dir(fileDir)
            if cover:
                if BaseDir.is_file_exists(filePath):
                    listdir = rawid.split("/")
                    cover_field = '/smartlib/jstorbook/' + listdir[0] + '/' + listdir[1] + '.jpg'
                    # sql = "update `modify_title_info_zt` set cover='{}' where rawid='{}'".format(cover_field, rawid)
                    listsql.append((rawid, cover_field))
                elif cover.find("data:image") != -1:
                    buff = ImageFile.get_image_to_base64(cover.split(",")[-1])
                    if ImageFile.img_to_format_jpg(buff, filePath):
                        listdir = rawid.split("/")
                        cover_field = '/smartlib/jstorbook/' + listdir[0] + '/' + listdir[1] + '.jpg'
                        # sql = "update `modify_title_info_zt` set cover='{}' where rawid='{}'".format(cover_field,rawid)
                        # listsql.append(sql)
                        listsql.append((rawid, cover_field))
                # if len(listsql) % 10000 == 0:
                #     self.sqlite3utiles.ExeSqlliteList(listsql, errExit=True)
                #     listsql.clear()

        if len(listsql) > 0:
            sql = "insert or ignore into `temp1`(`rawid`,`cover`) values (?,?)"
            self.sqlite3utiles.ExeSqlliteMany(sql, listsql, errExit=True)
            listsql.clear()

    def set_cover(self):
        sql = "UPDATE modify_title_info_zt SET cover=(select cover FROM temp1 WHERE modify_title_info_zt.rawid=temp1.rawid)"
        self.sqlite3utiles.ExeSqlliteSql(sql)

    def clear_temp(self):
        sql = "DROP TABLE IF EXISTS `temp1`"
        self.sqlite3utiles.ExeSqlliteSql(sql)


if __name__ == "__main__":
    filetoolsdb3 = FileToolsDB3()
    filetoolsdb3.set_config_file(config_file)
    for filepath in BaseDir.get_dir_all_files(r"C:\Users\xuzhu\Desktop\jstor"):
        filetoolsdb3.conn_sqlite3(filepath)
        sql = "select rawid,cover from `modify_title_info_zt`"
        filetoolsdb3.set_sql(sql)
        rows = filetoolsdb3.sqlite_select()
        filetoolsdb3.create_temp_tab()
        filetoolsdb3.deal_sqlite3_select(rows)
        filetoolsdb3.set_cover()
        filetoolsdb3.clear_temp()
